package com.spsy.order.service.impl;

import com.alibaba.fastjson2.JSON;
import com.spsy.common.core.domain.R;
import com.spsy.common.core.utils.DateUtils;
import com.spsy.common.vo.OrderAddParamsVo;
import com.spsy.order.domain.Order;
import com.spsy.order.domain.OrderLog;
import com.spsy.order.service.IOrderLogService;
import com.spsy.order.service.IOrderService;
import com.spsy.order.service.MqService;
import com.spsy.order.service.OrderOptsService;
import com.spsy.order.vo.OrderAddRequest;
import com.spsy.pay.api.PayApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

/**
 * @author: liuzhiping
 * @date: 2025/5/7 16:10
 **/
@Service
@Slf4j
public class OrderOptsServiceImpl implements OrderOptsService {

    @Autowired
    private PayApi payApi;

    @Autowired
    private IOrderService iOrderService;

    @Autowired
    private IOrderLogService iOrderLogService;

    @Autowired
    private MqService mqService;


    @Override
    public R sendPayOrder(OrderAddRequest orderAddRequest) throws Exception{
        log.info("参数 orderAddRequest:{}", JSON.toJSONString(orderAddRequest));

        Random random = new Random();
        int randomoperands = random.nextInt(4);
        //公司+当前时间+随机4位
        String orderId = "2209a"+ DateUtils.dateTimeNow()+randomoperands;

        //入库
        Order order = Order.builder()
                //订单编号 有规则的 唯一索引
                .orderNo(orderId).
                couponAmount(new BigDecimal((double)0.11))
                .discountAmount(new BigDecimal(0.22)).
                paymentAmount(new BigDecimal(3.00)).totalAmount(new BigDecimal(3.00)).
                paymentSerialNumber("2").
                paymentTime(new Date()).
                receiveTime(new Date()).
                paymentType(1).
                shippingAddressId((long)3).status(1).shippingCode("3").shippingFee(new BigDecimal(0.11))
                .totalAmount(new BigDecimal((double) 99.00)).userId(Long.valueOf(orderAddRequest.getUserId())).
                build();

        int insertOrderCount = iOrderService.insertOrder(order);

        log.info("insertOrderCount:{}", insertOrderCount);

        log.info("order:{}", JSON.toJSONString(order));


        //插入订单记录表
        OrderLog orderLog = OrderLog.builder()
                .orderId(order.getId())
                .orderNo(orderId)
                .build();
        int insertOrderLogCount = this.iOrderLogService.insertOrderLog(orderLog);


        log.info("insertOrderLogCount:{}", insertOrderLogCount);



        //发消息到延迟队列中，【为了帮助我们到了30分钟之后处理订单的状态  未支付--修改取消】
        this.mqService.sendMsg(orderId,20000);




        //调用微信的下单接口
        /*R r = this.payApi.payOrder( OrderAddParamsVo.builder().orderId(orderId).productId(orderAddRequest.getProductId()).build());
*/
        return R.ok();
    }
}
